package com.goodfather.textbook.youdao.pad.bean;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.goodfather.textbook.youdao.pad.pac.Constants;
import com.goodfather.textbook.youdao.pad.util.C;
import com.goodfather.textbook.youdao.pad.util.L;

/**
 * 用户管理
 */

public class UserManager {


    private static final String TAG = UserManager.class.getSimpleName();
    private static UserManager instance;
    private volatile UserData user;

    private UserManager() {

    }

    public static UserManager getInstance() {
        if (instance == null) {
            synchronized (UserManager.class) {
                if (instance == null) {
                    instance = new UserManager();
                }
            }
        }
        return instance;
    }

    public UserData getUser() {
        return user;
    }

    public boolean isLogin() {
        return getUser() != null && !TextUtils.isEmpty(getUser().sessionToken);
    }


    public void storeUserData(UserData userData) {
        user = userData;
        String json = user == null ? null : new Gson().toJson(user);
        C.setPreference(Constants.PREF_KEY_USER_DATA, new Gson().toJson(user));
    }

    //for logout or token expired
    public void removeUserData() {
        C.setPreference(Constants.PREF_KEY_USER_DATA, null);
        user = null;
        refreshTokenIfLogIn();
    }

    public void restoreUserData(){
        String json = C.getPreference(Constants.PREF_KEY_USER_DATA,null);
        L.d(TAG,"用户信息---->"+json);
        user = (json == null ? null : new Gson().fromJson(json, UserData.class));
        refreshTokenIfLogIn();
    }
    public void refreshTokenIfLogIn() {
//        if (isLogin()) {
//            HeaderManage.getInstance().setUserName(user.username);
//            HeaderManage.getInstance().setSessionToken(user.sessionToken);
//            HeaderManage.getInstance().setUserId(user.id);
//        } else {
//            HeaderManage.getInstance().setUserName(null);
//            HeaderManage.getInstance().setSessionToken(null);
//            HeaderManage.getInstance().setUserId(null);
//        }
    }
}
